package des;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * 配置读取类，从配置文件中读取key和保护口令
 *
 */
public class PropUtils {

    static String proName="application.properties";
    static Properties prop=null;
    public static boolean changePass=false;
    /**
     * 打开程序配置文件，配置文件存有密钥和key
     */
    public static Properties loadConfig() {
        if(prop!=null) {
            return prop;
        }
        InputStream in = null;
        try {
            in = PropUtils.class.getClassLoader().getResourceAsStream(proName);
            prop=new Properties();
            prop.load(in);
            return prop;
        } catch (IOException e) {
            e.printStackTrace();
        }
        close(in);
        return new Properties();
    }

    /**
     * 查询当前运行的jar在哪个目录
     */
    private static String findJarPath(String parent,int value) {
        String username = Constants.UserName;
        File parentF=new File(parent);
        if (!parentF.exists()) {
            System.out.println(parent + " dir not exist");
            return null;
        }
        File[] fs=parentF.listFiles();
        if (fs==null) {
            System.out.println(parent + " dir not exist");
            return null;
        }
        for (File f:fs) {
            if (value == 0) {
                if (f.getName().endsWith("GenKey.jar")) {
                    System.out.println("found jar:" + f.getAbsolutePath());
                    return f.getAbsolutePath();
                }
            }
            if (value == 1) {
                if (f.getName().endsWith(username + ".jar")) {
                    System.out.println("found jar:" + f.getAbsolutePath());
                    return f.getAbsolutePath();
                }
            }
        }
        return null;
    }

    /**
     * 打开程序配置文件，配置文件存有密钥和key
     */
    public static void storeConfig(Properties prop,String password) {
        OutputStream out=null;
        try {
            if (password!=null) {
                String seedKey= Constants.seedKey;
                //生成口令
                String EncryptKey = AES.aesEncry(seedKey,password);
                //保存配置文件
                prop.setProperty("protectedPwd",password);
                prop.setProperty("EncryptKey", EncryptKey);
                changePass=true;               //是否已修改密码
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        close(out);
    }

    /**
     * 改变c
     */
    public static void CountConfig(Properties prop, String c) {
        OutputStream out=null;
        System.out.println("c = " + c);
        int newc = Integer.parseInt(c) + 1;
        System.out.println("newc = " + newc);
        prop.setProperty("c",String.valueOf(newc));
        changePass=true;
        close(out);
    }

    /**
     * 关闭资源
     */
    private static void close(Closeable ch) {
        if(ch!=null) {
            try {
                ch.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 配置内容写回配置文件
     */
    public static void saveConfig(int value) {
        String jarDir = null;
        String username = Constants.UserName;
        if (!changePass) {
            System.out.println("1");
            return;
        }
        URL url = PropUtils.class.getClassLoader().getResource(proName);
        File proFile = new File(url.getFile());
        System.out.println(proFile);
        if (proFile.exists()) {
            try {
                //如果文件系统存在配置文件，在诶不运行则直接修改
                prop.store(new FileOutputStream(proFile), null);
            } catch (Exception e) {
                e.printStackTrace();;
            }
            return;
        }
        //查询jar所在路径
        System.out.println("path="+url.getPath());
        System.out.println("file="+url.getFile());
        //URL去掉资源定位符file协议前缀和jar末尾字符标志
        if (value == 0) {
            jarDir=url.getPath().substring("file:/".length(),url.getPath().indexOf("GenKey.jar"));
            System.out.println("new = " + jarDir);
        }
        if (value == 1) {
            System.out.println(username + ".jar");
            jarDir=url.getPath().substring("file:/".length(),url.getPath().indexOf(username + ".jar"));
            System.out.println("new = " + jarDir);
        }
        System.out.println("file2="+jarDir);
        String path=findJarPath(jarDir,value);
        if (path==null) {
            return;
        }
        CopyJarUtil d = new CopyJarUtil();
        try {
            String newPath=null;
            if (value == 0) {
                newPath = path.substring(0,path.lastIndexOf("GenKey.jar"))+username + ".jar";
            }
            if (value == 1) {
                newPath = path.substring(0,path.lastIndexOf(".jar"))+"x.jar";
            }
            System.out.println(newPath);
            File srcJar=new File(path);
            File tarJar=new File(newPath);
            //拷贝jar的内容，替换为新的配置内容
            if (value == 0) {
                d.copyJarByJarFile(srcJar,tarJar,proName,prop);
                //删除原来的jar
                srcJar.deleteOnExit();
            }
            if (value == 1) {
                d.copyJarByJarFile(srcJar,tarJar,proName,prop);
                d.copyJarByJarFile(tarJar,srcJar,proName,prop);
                tarJar.deleteOnExit();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
